<?php


namespace app\app\controller;


use app\common\controller\Homebase;
use EasyWeChat\Factory;
use think\Db;
use function Symfony\Component\String\b;

class Member extends Homebase
{
    protected $token;
    protected $memberInfo;
    protected $memberId;

    protected function initialize()
    {
        parent::initialize();
        $authorization = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
        if (empty($authorization)) {
            responseJson(-100, '请先登录');
        }
        $token = trim($authorization);
        $member = Db::name('member')->where('access_token', '=', $token)->find();
        if (!$member) {
            responseJson(-100, '登录信息有误');
        }
        $this->token = $token;
        $this->memberInfo = $member;
        $this->memberId = $member['id'];
    }

    public function getMemberInfo()
    {
        msg(0, '查询成功', $this->memberInfo);
    }

    //查询价格
    public function queryPrice()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
//            $queryNum=useQueryNum($this->memberId);
//            if ($queryNum==-1){
//                msg(-1, '查询余额不足', '');
//            }
            $inert_data = array(
                'name' => $data['name'],
                'ji_data' => strtotime($data['ji_data']),
                'area' => $data['area'],
                'price' => $data['price'],
                'start_time' => strtotime($data['start_time']),
                'desc' => $data['desc'],
                'create_time' => time(),
                'status' => 0,
                'member_id' => $this->memberId
            );
            if ($data['imgs']) {
                $inert_data['imgs'] = implode(',', $data['imgs']);
            }
            $query_order_id = Db::name('query_order')->insertGetId($inert_data);
//            $data['files'] = array(
//                ['url' => 'https://ybhxcx.lmweixin.com//uploads/images/20250313/a82b23b74cc3cef4ec890495e934c340.png',
//                    'name' => '图2.png'
//                ],
//                ['url' => 'https://ybhxcx.lmweixin.com//uploads/images/20250313/a82b23b74cc3cef4ec890495e934c340.png',
//                    'name' => '图3.png'
//                ],
//            );
            if ($data['files']) {
                foreach ($data['files'] as $k => $v) {
                    $insert_data = array(
                        'query_order_id' => $query_order_id,
                        'url' => $v['url'],
                        'file_name' => $v['name'],
                        'sort' => $k + 1
                    );
                    Db::name('query_order_file')->insertGetId($insert_data);
                }
            }
            //去掉 后台扣费的时候增加消息
//            $content=$data['name'].'估价使用查询次数1次。';
//            sendMsg(2, '查询次数使用', $content, $this->memberId);
            Db::commit();
            msg(0, '创建成功', $query_order_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //todo todo 汽配报价
    public function queryPrice2()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            $inert_data = array(
                'order_type' => 2,
                'name' => $data['name'],//单位名称
                'people' => $data['people'],//联系人
                'link_type' => $data['link_type'],//联系方式
                'cz' => $data['cz'],//传真
                'e_mail' => $data['e_mail'],//电子邮件
                'brand_id' => $data['brand_id'],//品牌型号
                'car_no' => $data['car_no'],//车辆识别码
                'init_data' => $data['init_data'],//初次登记日期 2025-09-26
                'qw_type' => $data['qw_type'],//期望类型 1、市场价 2、4s价格
                'is_j' => $data['is_j'],//是否加急 1普通 2加急
                'create_time' => time(),
                'remark' => $data['remark'],//备注
                'member_id' => $this->memberId
            );
            $query_order_id = Db::name('query_order')->insertGetId($inert_data);
            if ($data['files']) {
                foreach ($data['files'] as $k => $v) {
                    $insert_data = array(
                        'query_order_id' => $query_order_id,
                        'url' => $v['url'],
                        'file_name' => $v['name'],
                        'sort' => $k + 1
                    );
                    Db::name('query_order_file')->insertGetId($insert_data);
                }
            }
            Db::commit();
            msg(0, '创建成功', $query_order_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //获取查询列表
    public function getQueryPriceList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['member_id', '=', $this->memberId];
        $where[] = ['is_del', '=', 0];
        if (isset($data['type']) && $data['type']) {
            $where[] = ['order_type  ', '=', $data['type']];
        }
        //1报价中 2报价完成
        if (isset($data['status']) && $data['status']) {
            if ($data['status'] == 1) {
                $where[] = ['status  ', '=', 0];
            }
            if ($data['status'] == 2) {
                $where[] = ['status  ', '=', 1];
            }
        }
        $data_list = Db::name('query_order')
            ->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                $item['ji_data'] = date('Y-m-d H:i:s', $item['ji_data']);
                $item['start_time'] = date('Y-m-d H:i:s', $item['start_time']);
                if ($item['status_time']) {
                    $item['status_time'] = date('Y-m-d H:i:s', $item['status_time']);
                }
                return $item;
            });
        msg(0, '查询成功', $data_list);
    }

    //获取查询详情
    public function queryPriceDetail()
    {
        $data = $this->request->param();
        $return_data = Db::name('query_order')->find($data['id']);
        if (!$return_data) {
            msg(-1, '订单不存在', '');
        }
        $return_data['imgs'] = explode(',', $return_data['imgs']);
        $query_order_file = Db::name('query_order_file')->where([
            'query_order_id' => $return_data['id']
        ])->select();
        $relativePath = str_replace(conf("wechat", "url"), '', $return_data['assess_file']);
        $assess_file = Db::name('attachment')->where('path', '=', $relativePath)->find();
        $return_data['assess_file_name'] = '';
        if ($assess_file) {
            $return_data['assess_file_name'] = $assess_file['name'];
        }
        $return_data['create_time'] = date('Y-m-d H:i:s', $return_data['create_time']);
        if ($return_data['ji_data']) {
            $return_data['ji_data'] = date('Y-m-d H:i:s', $return_data['ji_data']);
        }
        if ($return_data['start_time']) {
            $return_data['start_time'] = date('Y-m-d H:i:s', $return_data['start_time']);
        }
        if ($return_data['brand_id']) {
            $brand_info = Db::name('brand')->find($return_data['brand_id']);
            $return_data['brand_info'] = $brand_info;
        }
        $return_data['query_order_file'] = $query_order_file;
        msg(0, '查询成功', $return_data);
    }

    //专家查询
    public function zhuanjiaQuery()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            $insert_data = array(
                'demand' => $data['demand'],
                'require' => $data['require'],
                'content' => $data['content'],
                'content_cate_id' => $data['content_cate_id'],
                'opinion' => $data['opinion'],
                'message_info' => $data['message_info'],
                'member_id' => $this->memberId,
                'server_time' => $data['server_time'],
                'create_time' => time(),
            );
            $expert_order_id = Db::name('expert_order')->insertGetId($insert_data);
            Db::commit();
            msg(0, '修改成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //获取找专家列表
    public function zjQueryList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['member_id', '=', $this->memberId];
        $where[] = ['is_del', '=', 0];
        $data_list = Db::name('expert_order')->where($where)->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                return $item;
            });
        msg(0, '查询成功', $data_list);
    }

    //获取找专家详情
    public function zjQueryDetail()
    {
        $data = $this->request->param();
        $where[] = ['member_id', '=', $this->memberId];
        $where[] = ['is_del', '=', 0];
        $return_data = Db::name('expert_order')
            ->alias('eo')
            ->join('content_cate cc', 'eo.content_cate_id=cc.id')
            ->field('eo.*,cc.name as cate_name')
            ->find($data['id']);
        $return_data['create_time'] = date('Y-m-d H:i:s', $return_data['create_time']);
        msg(0, '查询成功', $return_data);
    }


    //创建评估
    public function createAccess()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            $insert_data = array(
                'member_id' => $this->memberId,
                'create_time' => time(),
                'people' => $data['people'],
                'phone' => $data['phone'],
                'access_msg' => $data['access_msg'],
                'example_desc' => $data['example_desc'],
            );
            $access_id = Db::name('access')->insertGetId($insert_data);
            Db::commit();
            msg(0, '创建成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //谈合作
    public function createCooperate()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            $insert_data = array(
                'member_id' => $this->memberId,
                'create_time' => time(),
                'name' => $data['name'],
                'phone' => $data['phone'],
                'content' => $data['content'],
            );
            $access_id = Db::name('cooperate')->insertGetId($insert_data);
            Db::commit();
            msg(0, '修改成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //退出
    public function logout()
    {
        Db::startTrans();
        try {
            Db::name('member')->where('access_token', '=', $this->token)->update(
                [
                    'access_token' => null,
                ]
            );
            Db::commit();
            msg(0, '退出完成', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //修改密码
    public function updatePassword()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            if ($data['password1'] != $data['password2']) {
                msg(-1, '两次密码不正确', '');
            }
            if (!checkCode($this->memberInfo['mobile'], $data['verifyCode'])) {
                msg(-1, '验证码错误', '');
            }
            Db::name('member')->update([
                'id' => $this->memberId,
                'password' => md5($data['password1']),
            ]);
            Db::commit();
            msg(0, '修改完成', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //消息中心
    public function getMsg()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['member_id', '=', $this->memberId];
        $where[] = ['is_del', '=', 0];
        if (isset($data['msg_cate']) && $data['msg_cate']) {
            $where[] = ['message_cate_id', '=', $data['msg_cate']];
        }
        $msg_list = Db::name('message')
            ->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                return $item;
            });
        msg(0, '查询成功', $msg_list);
    }

    //规范标准列表
    public function getCompilation()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['is_del', '=', 0];
        $where[] = ['status', '=', 1];
        if (isset($data['name']) && $data['name']) {
            $where[] = ['name|gbt', 'like', '%' . $data['name'] . '%'];
        }
        if (isset($data['status']) && $data['status']) {
            $where[] = ['status', '=', $data['status']];
        }

        //近一月	strtotime('-1 month')	time()
        //近三月	strtotime('-3 months')	time()
        //近半年	strtotime('-6 months')	time()
        //近一年	strtotime('-1 year')	time()
        //近两年	strtotime('-2 years')	time()
        //近三年	strtotime('-3 years')	time()
        if (isset($data['data_type']) && $data['data_type']) {
            switch ($data['data_type']) {
                case 1:
                    $where[] = ['create_time', 'between', [strtotime('-1 month'), time()]];
                    break;
                case 2:
                    $where[] = ['create_time', 'between', [strtotime('-3 months'), time()]];
                    break;
                case 3:
                    $where[] = ['create_time', 'between', [strtotime('-6 months'), time()]];
                    break;
                case 4:
                    $where[] = ['create_time', 'between', [strtotime('-1 year'), time()]];
                    break;
                case 5:
                    $where[] = ['create_time', 'between', [strtotime('-2 years'), time()]];
                    break;
                case 6:
                    $where[] = ['create_time', 'between', [strtotime('-3 years'), time()]];
                    break;
                default:
                    // 默认情况（可选）
            }
        }
        $msg_list = Db::name('compilation')
            ->where($where)
            ->order('sort desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d', $item['create_time']);
                $item['effect_time'] = date('Y-m-d', $item['effect_time']);
                return $item;
            });
        msg(0, '查询成功', $msg_list);
    }

    //账户余额
    public function getMemberCount()
    {
//        $num = Db::name('member_account')->where([
//            ['member_id', '=', $this->memberId],
//            ['effect_data', '>=', time()],
//        ])->sum('count');
//        $return_data['num'] = $num;
//        $account = Db::name('member_account')->where([
//            ['member_id', '=', $this->memberId],
//            ['effect_data', '>=', time()],
//        ])->order('effect_data')->find();
        $return_data['num'] = $this->memberInfo['money'];
        $return_data['remind'] = '';
//        if ($account) {
//            $return_data['remind'] = '有' . $account['count'] . '次查询将于' . date('Y-m-d', $account['effect_data']) . '失效';
//        }
        msg(0, '查询成功', $return_data);
    }

    //账户列表
    public function accountList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 10);
        $where[] = ['status', '=', 1];
        $where[] = ['member_id', '=', $this->memberId];
        $msg_list = Db::name('member_account')
            ->where($where)
            ->order('effect_data desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d', $item['create_time']);
                $item['effect_data'] = date('Y-m-d', $item['effect_data']);
                $item['effect_status'] = 1;
                if ($item['effect_time'] <= time()) {
                    $item['effect_status'] = 0;
                }
                return $item;
            });
        msg(0, '查询成功', $msg_list);
    }

    //资金流水
    public function accountList2()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 10);
        $where[] = ['member_id', '=', $this->memberId];
        $msg_list = Db::name('money_record')
            ->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                return $item;
            });
        msg(0, '查询成功', $msg_list);
    }
}